package io.gitee.chearnee.fw.datasecurity.core.advice;

import io.gitee.chearnee.fw.datasecurity.core.annotation.control.DisableCrypt;
import io.gitee.chearnee.fw.datasecurity.core.properties.DataSecurityDbCryptProperty;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdvice;

import java.io.IOException;
import java.lang.reflect.Type;

/**
 * @author cn
 * @version 1.0
 * @description
 * @date 11/9/2022 4:30 PM
 */
@Slf4j
@Order(-10)
public class CryptRequestBodyAdvice implements RequestBodyAdvice {

    @Autowired
    private DataSecurityDbCryptProperty dataSecurityDbCryptProperty;


    @Override
    public boolean supports(MethodParameter methodParameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
        if (!dataSecurityDbCryptProperty.isEnabled()) {
            return false;
        }
        DisableCrypt disableCrypt = methodParameter.getDeclaringClass().getAnnotation(
                DisableCrypt.class);
        if (disableCrypt == null) {
            disableCrypt = methodParameter.getMethodAnnotation(DisableCrypt.class);
        }
        return disableCrypt == null;
    }

    @Override
    public HttpInputMessage beforeBodyRead(HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) throws IOException {
        return inputMessage;
    }

    @Override
    public Object afterBodyRead(Object body, HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
        return body;
    }

    @Override
    public Object handleEmptyBody(Object body, HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
        return body;
    }
}
